package jpa.ehcache;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.FlushModeType;

import com.opensymphony.xwork2.ActionSupport;
import com.ticket.dao.IDbDAO;

/**
 * @Description：
 * @author：涂有
 * @date 2015年12月24日 下午1:57:47
 */
public class TestAction extends ActionSupport{

	@Resource
	EntityManagerFactory manageFactory;
	@Resource
	IDbDAO<Person, String> dao;
	
	public String execute(){
		
		EntityManager manage = manageFactory.createEntityManager();
		EntityTransaction trans = manage.getTransaction();
		trans.begin();
		manage.setFlushMode(FlushModeType.COMMIT);
		Random rand = new Random();
		for(int i = 0; i < 10000000; i++){
			
			Person person = new Person();
			person.setId(UUID.randomUUID().toString());
			person.setName(Gen.getRandomJianHan(rand, 3));
			person.setAge(rand.nextInt(150));
			person.setBirth(new Date(rand.nextLong()/1000000));
			manage.persist(person);
			
			if(i % 1000 == 0){
				
				System.out.println(i);
				manage.flush();
				manage.clear();
			}
		}
		trans.commit();
		
		return SUCCESS;
	}
	
	public String get(){
		
		Person person = dao.get(Person.class, "0000fcc4-8a9e-4b07-a476-bfaae371667e");
		System.out.println(person.getId());
		return null;
	}
	
//	public String sql(){
//		
//		List<Person> person = dao.executeJPQLForQuery("select s from " + Person.class.getName() + " s", 
//				Person.class);
//		System.out.println(person);
//		return null;
//	}
	
	public String add(){
		
		Random rand = new Random();
		Person person = new Person();
		person.setId(UUID.randomUUID().toString());
		person.setName(Gen.getRandomJianHan(rand, 3));
		person.setAge(rand.nextInt(150));
		person.setBirth(new Date(rand.nextLong()/1000000));
		
		dao.persist(person);
		System.out.println(person.getId());
		return null;
	}
	
	public String update(){
		
		Person person = dao.get(Person.class, "1a656969-f1d9-4540-b47a-64a4544d1da1");
		
		person.setAge(55);
		dao.merge(person);
		return null;
	}
	
	public String delete(){
		
		List<Person> persons = dao.executeJPQLForQuery("select s from " + Person.class.getName() + " s", Person.class);
		if(persons.size() > 0){
			
			dao.remove(persons.get(0));
		}
		
		return null;
	}
	
	public String count(){
		
		Long count = dao.executeJPQLForQuerySingle("select count(s) from " + Person.class.getName() + " s", Long.class);
		System.out.println(count);
		return null;
	}
	
	public String list(){
		
		List<Person> persons = dao.executeJPQLForQuery("select s from " + Person.class.getName() + " s", Person.class);
		System.out.println(persons.size());
		return null;
	}
}
